package com.lntea.jdbc.dbcp;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.lntea.jdbc.dbutils.User;

public class BasicDataSourceDemo {
	public static void main(String[] args) {
		BasicDataSource basicDataSource = new BasicDataSource();
		basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
		basicDataSource.setUrl("jdbc:mysql://localhost:3306/jfinalweb");
		basicDataSource.setUsername("root");
		basicDataSource.setPassword("root");
		
		Connection conn = null;
		try {
			conn = basicDataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		execQuery(conn);
	}

	static void execQuery(Connection conn) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("password_salt", "passwordSalt");
		BeanProcessor customBeanProcessor = new BeanProcessor(map);
		ResultSetHandler<List<User>> h = new BeanListHandler<User>(User.class,new BasicRowProcessor(customBeanProcessor));

		QueryRunner queryRunner = new QueryRunner();
		List<User> users = null;
		try {
			users = queryRunner.query(conn, "select * from users", h);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (User user : users)
			System.out.println(user);
	}
}
